'use strict';

const Controller = require('egg').Controller;
const jwt=require('jsonwebtoken')
const {md5Pwd}=require('../../utils/index')

class LoginController extends Controller {
    async index() {
        const { ctx } = this;
        const {username,password}=ctx.request.body
        const post = await this.app.mysql.get('userlist', { username: `${username}`,password:`${password}` });
        if(post){
            ctx.body={
                code:200,
                mes:'登陆成功',
                token:jwt.sign({username},'1906A')
            }
        }else{
            ctx.body={
                code:401,
                mes:'登陆失败'
            }
        }

    }
    async signIn() {
        const { ctx } = this;
        const {username,password,nickname}=ctx.request.body
        const post = await this.app.mysql.get('userlist', { username: `${username}`});
        if(post){
            ctx.body={
                code:200,
                mes:'该账号已被注册',
            }
        }else{
            const result = await this.app.mysql.query(`INSERT INTO userlist (username, password, nickname, id) VALUES ('${username}', '${md5Pwd(password)}', '${nickname}', NULL)`);
            if(result.affectedRows){
                ctx.body={
                    code:200,
                    mes:'注册成功'
                }
            }else{
                ctx.body={
                    code:303,
                    mes:'注册失败'
                }
            }
        }

    }
}

module.exports = LoginController;
